package com.fable.hardware.temperature;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.serotonin.util.queue.ByteQueue;

import java.text.DecimalFormat;
import java.util.Random;

public class MainActivity extends AppCompatActivity {

    protected static final String LOGGER_TAG = ModbusTcpUtil.class.getName();

    private TextView tvTemperature; //温度
    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvTemperature = (TextView) findViewById(R.id.tvTemperature);

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 0:
                        tvTemperature.setText(msg.obj + "℃");
                }
            }
        };
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    while (true) {
                        Message message = new Message();
                        message.obj = new DecimalFormat("#.00").format(pullTemperature());
                        message.what = 0;
                        handler.sendMessage(message);
                        Thread.currentThread().sleep(1000);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }

    /**
     * 获取温度
     */
    public double pullTemperature() {
        String ip = "192.168.1.10";
        int port = 502;
        int slaveId = 255;
        int start = 40600;
        int readLength = 16;

        ByteQueue byteQueue = ModbusTcpUtil.readHoldingRegisters(ip, port, slaveId, start, readLength);
        byte[] bytes = new byte[4];
        bytes[0] = byteQueue.peek(5);
        bytes[1] = byteQueue.peek(6);
        bytes[2] = byteQueue.peek(3);
        bytes[3] = byteQueue.peek(4);

        // Test
//        ByteQueue byteQueue = new ByteQueue();
//        byte[] bytes = new byte[4];
//        bytes[0] = (byte) 0x46;
//        bytes[1] = (byte) 0x9C;
//        bytes[2] = (byte) 0x40;
//        bytes[3] = (byte) 0x00;

        String currentBytesString = bytes2HexString(bytes); //电流量字符串
        float current = bytes2Float(bytes); //电流量
        double temperature = current2Temperature(current, 4000, 20000, 0, 300);//温度

        Log.d(LOGGER_TAG, "receive bytes:" + byteQueue);
        Log.d(LOGGER_TAG, "current bytes:" + currentBytesString);
        Log.d(LOGGER_TAG, "current:" + current + " uA");
        Log.d(LOGGER_TAG, "temperature: " + temperature + " ℃");

        return temperature;
    }

    /**
     * 电流量转换温度
     *
     * @param current    电流量，单位uA
     * @param currentMin 量程最小电流，单位uA
     * @param currentMax 量程最大电流，单位uA
     * @param tempMix    量程最小温度，单位℃
     * @param tempMax    量程最大温度，单位℃
     * @return 温度，单位℃
     */
    public double current2Temperature(double current, double currentMin, double currentMax, double tempMix, double tempMax) {
        return (tempMax - tempMix) / (currentMax - currentMin) * (current - currentMin);
    }

    /**
     * 字节数组转单精度浮点数
     *
     * @param b 字节数组
     * @return 单精度浮点数
     */
    public static float bytes2Float(byte[] b) {
        int bits = 0;
        for (int i = 0; i < 4; i++) {
            bits |= (b[i] & 0xff) << (3 - i) * 8;
        }
        return Float.intBitsToFloat(bits);
    }

    /**
     * 字节数组转换成十六进制字符串
     *
     * @param b 字节数组
     * @return 十六进制字符串
     */
    public String bytes2HexString(byte[] b) {
        String ret = "";
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = "0" + hex;
            }
            ret += hex.toUpperCase();
        }
        return ret;
    }
}
